package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"shop/models"
)

type ShopController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	intro := c.GetString("intro")
	shop := models.Shop{
		Name:  name,
		Price: price,
		Intro: intro,
	}
	err := models.Add(&shop)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	var shop []models.Shop
	err := models.DB.Find(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}

// 修改
func (c *ShopController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	intro := c.GetString("intro")
	shop := models.Shop{
		Model: gorm.Model{ID: uint(id)},
		Name:  name,
		Price: price,
		Intro: intro,
	}
	err := models.DB.Updates(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
